package com.example.administrator.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpContect  {
    private Handler mHandler;
    protected String target = "http://soymilk.nfc100.cn/";
    private int error;
    private String message;
    private Context mContext;


    public String send(String route, String data ) {
            String returnCode="";
        String target;
        target = this.target+route;
        try {
            URL url = new URL(target);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.getOutputStream().write(data.getBytes());
            int code = connection.getResponseCode();
            if (code==200){
                /*connection.setDoOutput(true);*/
                InputStream inputStream=connection.getInputStream();
                ByteArrayOutputStream bw=new ByteArrayOutputStream();
                int length=-1;
                byte[] buffer=new byte[1024];
                while ((length=inputStream.read(buffer))!=-1){
                    bw.write(buffer,0,length);
                }
                if (inputStream!=null){
                    returnCode=bw.toString();

                    inputStream.close();

                }
                connection.disconnect();
                JSONObject jsonObject=new JSONObject(returnCode);
                 error=jsonObject.optInt("error");
                 message=jsonObject.optString("message");
                 if (error==0){
                     return returnCode;
                 }
                else if (error==4){
                     mContext.getApplicationContext();
                     Toast.makeText(mContext,message,Toast.LENGTH_SHORT).show();

                 }
                 /*else if (error==9){
                     mContext.getApplicationContext();
                     Toast.makeText(mContext,message,Toast.LENGTH_SHORT).show();
                 }*/
            }
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }


        return null;

    }


}
